package com.ky.pro.java.concurrency;

import com.ky.pro.java.concurrency.algo.FiboUtil;

import java.util.concurrent.CountDownLatch;

/**
 * @ClassName CountdownLatchMain
 * @Description 使用CDL实现
 * @Date 2021/11/27 9:45
 * @Author kevin
 **/
public class CountdownLatchMain {

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法

        CountDownLatch latch = new CountDownLatch(1);
        FiboCountDownLatchTask task = new FiboCountDownLatchTask(latch);
        new Thread(task).start();
        latch.await();

        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + task.getResult());

        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

        // 然后退出main线程
    }

    static class FiboCountDownLatchTask implements Runnable {

        private CountDownLatch latch;

        int result;

        FiboCountDownLatchTask(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            result = FiboUtil.fibo(36);
            latch.countDown();
        }

        public int getResult() {
            return result;
        }
    }

}
